import { Button, Form, Input, Modal, Space } from "antd";
import React, { useState } from "react";
import { updateForm as updateInput } from "../../../utils/utils/setInput";
import { userApi } from "../../../utils/backend/server";
import { toast } from "../../Toast/Toast";
import { useAppDispatch, useAppSelector } from "../../../utils/store/hooks";
import {
  updateLogin,
  updateRegister,
  updateToken,
} from "../../../utils/store/deviceSlice";
import { AxiosResponse } from "axios";
import styles from "./Login.module.css";

export type User = {
  id?: number;
  name: string;
  mail?: string;
  password: string;
  phone?: number;
};

export type UpdateFormType = (
  e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
) => void;

export const PasswordInput = (props: {
  password: string;
  updateForm: UpdateFormType;
}) => {
  return (
    <Form.Item
      label="password"
      name="password"
      rules={[{ required: false, message: "Please input your password!" }]}
    >
      <Input
        type="password"
        name="password"
        value={props.password}
        onChange={props.updateForm}
      />
    </Form.Item>
  );
};

export const NameInput = (props: {
  name: string;
  updateForm: UpdateFormType;
}) => {
  return (
    <Form.Item
      label="name"
      name="name"
      rules={[{ required: false, message: "Please input your name!" }]}
    >
      <Input name="name" value={props.name} onChange={props.updateForm} />
    </Form.Item>
  );
};

/**
  show: boolean;
  close: () => void;
  showRegister: () => void;
 */
export const Login = () => {
  const [form, setForm] = useState<User>({
    name: "",
    password: "",
  });
  const dispatch = useAppDispatch();
  const info = useAppSelector((data) => data.device);
  const updateForm = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => updateInput(e, setForm);

  const check = () => {
    if (form.name === "" || form.name.length < 6) {
      toast("please check name");
      throw Error("name");
    }
    if (form.password === "" || form.password.length < 6) {
      toast("please check password");
      throw Error("password");
    }
  };

  const handleOk = async () => {
    check();
    try {
      const user = await userApi.login(form);
      toast(user.msg);
      if (!user.success) return;
      localStorage.setItem("Authorization", user.token);
      dispatch(updateToken(user.token));
      // props.close();
      dispatch(updateLogin(false));
    } catch (err) {
      const msg = (err as AxiosResponse<{ msg: string }>).data.msg;
      toast(msg);
    }
  };

  return (
    <Modal
      open={info.showLogin}
      onCancel={() => dispatch(updateLogin(false))}
      destroyOnClose={true}
      footer={<></>}
    >
      <Form
        name="basic"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: false }}
        autoComplete="off"
        onFinish={handleOk}
      >
        <NameInput name={form.name} updateForm={updateForm} />
        <PasswordInput password={form.password} updateForm={updateForm} />
        <Form.Item label={""}>
          <div className={styles.end}>
            <Space>
              <Button
                color="primary"
                onClick={() => dispatch(updateRegister(true))}
              >
                register
              </Button>
              <Button type="primary" htmlType="submit">
                Submit
              </Button>
            </Space>
          </div>
        </Form.Item>
      </Form>
    </Modal>
  );
};
